<template>
  <div class="login-container">
    <div class="login-background"></div>
    <div class="login-card">
      <div class="login-header">
        <div class="logo-section">
          <img src="@/assets/electron.svg" alt="Logo" class="login-logo" />
          <h1 class="login-title">欢迎使用</h1>
          <p class="login-subtitle">请输入您的账号信息登录</p>
        </div>
      </div>

      <div class="login-form">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          size="large"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入账号"
              prefix-icon="User"
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <div class="login-options">
              <el-checkbox v-model="loginForm.remember">记住账号</el-checkbox>
              <el-link type="primary" :underline="false">忘记密码？</el-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              @click="handleLogin"
              class="login-button"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="login-footer">
        <p class="copyright">© 2024 Electron Vue3 App. All rights reserved.</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useAppStore } from '@/store/index'

const router = useRouter()
const appStore = useAppStore()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  remember: false,
})

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度应为3-20个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' },
  ],
}

// 等待服务就绪
const waitForService = (maxWait = 5000) => {
  return new Promise((resolve, reject) => {
    const startTime = Date.now()
    const checkService = () => {
      const userService = (window as any).userService
      if (userService) {
        resolve(userService)
        return
      }

      if (Date.now() - startTime > maxWait) {
        reject(new Error('服务加载超时'))
        return
      }

      setTimeout(checkService, 100)
    }
    checkService()
  })
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) {
      return
    }
    loading.value = true

    // 等待服务就绪
    const userService = (window as any).userService
    // 调用主进程的登录服务
    userService
      .login(loginForm.username, loginForm.password)
      .then((result) => {
        if (result.success && result.userInfo && result.token) {
          // 使用store保存登录状态
          appStore.login(result.userInfo)

          // 保存token到localStorage
          localStorage.setItem('authToken', result.token)

          // 如果选择记住账号，保存到localStorage
          if (loginForm.remember) {
            localStorage.setItem('rememberedUsername', loginForm.username)
          } else {
            localStorage.removeItem('rememberedUsername')
          }

          ElMessage.success(result.message || '登录成功！')

          // 跳转到首页
          router.push('/')
        } else {
          ElMessage.error(result.message || '登录失败')
        }
      })
      .catch((error) => {
        ElMessage.error(error.message || '登录失败')
      })
  } finally {
    loading.value = false
  }
}

// 页面初始化时检查是否有记住的账号
const initForm = () => {
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    loginForm.username = rememberedUsername
    loginForm.remember = true
  }
}

// 初始化表单
initForm()
</script>

<style scoped lang="scss">
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #084498 0%, #1e40af 50%, #3b82f6 100%);
  overflow: hidden;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/wavy-lines.svg');
  background-size: cover;
  background-position: center;
  opacity: 0.1;
  z-index: 0;
}

.login-card {
  position: relative;
  z-index: 1;
  width: 420px;
  max-width: 90vw;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  animation: slideUp 0.8s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-section {
  .login-logo {
    width: 64px;
    height: 64px;
    margin-bottom: 20px;
    filter: drop-shadow(0 4px 8px rgba(8, 68, 152, 0.3));
    animation: float 3s ease-in-out infinite;
  }

  .login-title {
    font-size: 28px;
    font-weight: 700;
    color: #1f2937;
    margin: 0 0 8px 0;
  }

  .login-subtitle {
    font-size: 14px;
    color: #6b7280;
    margin: 0;
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-6px);
  }
}

.login-form {
  :deep(.el-form-item) {
    margin-bottom: 24px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 12px;
    padding: 12px 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    border: 1px solid #e5e7eb;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(8, 68, 152, 0.1);
      border-color: #084498;
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(8, 68, 152, 0.2);
      border-color: #084498;
    }
  }

  :deep(.el-input__inner) {
    font-size: 16px;
    color: #374151;

    &::placeholder {
      color: #9ca3af;
    }
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  :deep(.el-checkbox__label) {
    color: #6b7280;
    font-size: 14px;
  }

  :deep(.el-link) {
    font-size: 14px;
    font-weight: 500;
  }
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: linear-gradient(135deg, #084498 0%, #1e40af 100%);
  border: none;
  transition: all 0.3s ease;

  &:hover {
    background: linear-gradient(135deg, #0653a3 0%, #2563eb 100%);
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(8, 68, 152, 0.3);
  }

  &:active {
    transform: translateY(0);
  }

  &.is-loading {
    background: #9ca3af;

    &:hover {
      background: #9ca3af;
      transform: none;
      box-shadow: none;
    }
  }
}

.login-footer {
  text-align: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f3f4f6;

  .copyright {
    font-size: 12px;
    color: #9ca3af;
    margin: 0;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-card {
    padding: 30px 24px;
    margin: 20px;
  }

  .login-header {
    margin-bottom: 30px;

    .login-title {
      font-size: 24px;
    }
  }
}
</style>
